var express = require("express");
var router = express.Router();
const axios = require("axios");
const { APPURL, getApiUrl, postApiUrl } = require("./config");
/**
 * node代理转发
 */
getApiUrl.forEach((item) => {
  router.get(item, async function (req, res, next) {
    try {
      // 动态url，替换一下
      if (req.params.id) {
        const id = req.params.id;
        const newUrl = item.replace(/(:[^\/]+)/, id);
        const apiResponse = await axios.get(APPURL + newUrl);
        // 返回 API 响应给前端
        res.json(apiResponse.data);
      } else {
        // 静态直接转发
        // 发起实际的 API 请求
        const apiResponse = await axios.get(APPURL + item);
        // 返回 API 响应给前端
        res.json(apiResponse.data);
      }
    } catch (error) {
      // 处理错误
      console.error("GET Error fetching data from API:", error.message);
      res.status(500).json({ error: "Internal Server Error" });
    }
  });
});
postApiUrl.forEach((item) => {
  router.post(item, async function (req, res, next) {
    try {
      //发起实际的API请求
      const apiResponse = await axios.post(APPURL + item, req.body);
      //返回API响应给前端
      res.json(apiResponse.data);
    } catch (error) {
      //处理错误
      console.error("POST Error fetching data from API:", error.message);
      res.status(500).json({ error: "Internal Server Error" });
    }
  });
});
module.exports = router;
